﻿using System;
using System.Security.Cryptography;
using System.Text;

namespace Smarly.Bussines
{
	public class Password
	{
		public string PasswordString { get; set; }
		public string PasswordHash { get; set; }
		public string PasswordSalt { get; set; }

		private static string GenerateSalt()
		{
			var buf = new byte[16];
			(new RNGCryptoServiceProvider()).GetBytes(buf);
			return Convert.ToBase64String(buf);
		}

		public void EncodePassword()
		{
			PasswordSalt = PasswordSalt ?? GenerateSalt();
			byte[] bytes = Encoding.Unicode.GetBytes(PasswordString);
			byte[] src = Encoding.Unicode.GetBytes(PasswordSalt);
			var dst = new byte[src.Length + bytes.Length];
			Buffer.BlockCopy(src, 0, dst, 0, src.Length);
			Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length);
			HashAlgorithm algorithm = HashAlgorithm.Create("SHA1");
			byte[] inArray = algorithm.ComputeHash(dst);
			PasswordHash = Convert.ToBase64String(inArray);
		}

		public bool IsValide()
		{
			if (string.IsNullOrWhiteSpace(PasswordString) || string.IsNullOrWhiteSpace(PasswordSalt) ||
					string.IsNullOrWhiteSpace(PasswordHash))
				return false;

			string prevHash = PasswordHash;
			EncodePassword();
			return prevHash == PasswordHash;
		}
	}
}